package com.yifei.aspect;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONUtil;
import com.yifei.annotation.Log;
import com.yifei.constants.SecurityConstants;
import com.yifei.model.entity.auth.SysUserDetails;
import com.yifei.model.entity.system.SysOperateLog;
import com.yifei.model.enums.OperatorStatusEnum;
import com.yifei.model.form.auth.LoginFrom;
import com.yifei.service.system.SysOperateLogService;
import com.yifei.utils.AddressUtil;
import com.yifei.utils.IpUtil;
import com.yifei.utils.SecurityUtil;
import eu.bitwalker.useragentutils.UserAgent;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.NamedThreadLocal;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Executor;

/**
 * @Description: aop 打印日志
 * @Author: yiFei
 * @date: 2022/8/10 19:56
 */
@Aspect
@Component
public class LogAspect {

    private static final Logger log1 = LoggerFactory.getLogger(LogAspect.class);

    @Autowired
    @Qualifier("taskExecutor")
    private Executor taskExecutor;

    @Autowired
    private SysOperateLogService sysOperateLogService;

    /**
     * 计算操作消耗时间
     */
    private static final ThreadLocal<Long> TIME_THREAD_LOCAL = new NamedThreadLocal<>("Cost Time");
    /**
     * 未登录用户名
     */
    public static final String OPERATOR_DEFAULT_NAME = "游客";


    /**
     * 处理请求前执行
     */
    @Before(value = "@annotation(controllerLog)")
    public void boBefore(JoinPoint joinPoint, Log controllerLog) {
        TIME_THREAD_LOCAL.set(System.currentTimeMillis());
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) {
        handleLog(joinPoint, controllerLog, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e) {
        handleLog(joinPoint, controllerLog, e, null);
    }

    private void handleLog(JoinPoint joinPoint, Log controllerLog, Exception e, Object jsonResult) {
        try {
            SysOperateLog sysOperateLog = new SysOperateLog();
            // 1. 填写请求头信息
            HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
            // 1.1 获取请求方式
            sysOperateLog.setRequestMethod(request.getMethod());
            // 1.2 获取请求 ip
            sysOperateLog.setOperatorIp(IpUtil.getIpAddr(request));
            // 1.3 获取请求 url
            sysOperateLog.setOperatorUrl(substring(request.getRequestURI(), 0, 255));
            // 2. 解析方法名
            sysOperateLog.setMethod(joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()");
            // 3. 解析当前线程操作的用户
            SysUserDetails user = SecurityUtil.getUser();
            if (ObjectUtils.isEmpty(user)) {
                // 3.1 如果是登录请求，查看响应内容中的令牌，方便判断谁登录
                if (request.getRequestURI().equals(SecurityConstants.SECURITY_LOGIN_PATH)) {
                    sysOperateLog.setOperatorName(((LoginFrom) joinPoint.getArgs()[0]).getUsername());
                } else {
                    sysOperateLog.setOperatorName(OPERATOR_DEFAULT_NAME);
                }
            } else {
                // 3.2 设置当前线程操作的用户名
                sysOperateLog.setOperatorName(user.getUsername());
            }
            // 4. 获取 user-agent 方便后续获取 os，browser
            String headerUserAgent = request.getHeader("User-Agent");
            // 4.1 解析 userAgent
            UserAgent userAgent = UserAgent.parseUserAgentString(headerUserAgent);
            // 4.2 填写 userAgent 信息 （浏览器及操作系统）
            sysOperateLog.setOperatorBrowser(userAgent.getBrowser().getName());
            sysOperateLog.setOperatorOs(userAgent.getOperatingSystem().getName());
            // 5. 解析@Log参数
            getControllerMethodDescription(joinPoint, request, controllerLog, sysOperateLog, jsonResult);
            // 6. 记录是否操作成功
            if (ObjectUtils.isEmpty(e)) {
                sysOperateLog.setStatus(OperatorStatusEnum.OK);
            } else {
                sysOperateLog.setStatus(OperatorStatusEnum.ERROR);
                sysOperateLog.setErrorMsg(substring(e.getMessage(), 0, 2000));
            }
            // 5. 计算消耗时间
            sysOperateLog.setCostTime(System.currentTimeMillis() - TIME_THREAD_LOCAL.get());

            // 6. 耗时任务异步执行（ 解析地址以及保存日志信息... ） XXX 建议延迟一段时间后执行 ( 觉得耗时可全部异步 )
            taskExecutor.execute(saveLogTask(sysOperateLog));
        } catch (Exception error) {
            log1.error("记录日志时发生错误 ： ", error);
        } finally {
            TIME_THREAD_LOCAL.remove();
        }

    }


    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param request       请求信息
     * @param controllerLog 日志注解
     * @param sysOperateLog 操作日志
     */
    private void getControllerMethodDescription(JoinPoint joinPoint, HttpServletRequest request, Log controllerLog, SysOperateLog sysOperateLog, Object jsonResult) {
        // 1. 解析 @Log 信息
        sysOperateLog.setTitle(controllerLog.title());
        sysOperateLog.setBusinessType(controllerLog.businessType());
        sysOperateLog.setOperatorType(controllerLog.operatorType());
        // 2. 是否保存请求参数
        if (controllerLog.isSaveRequestData()) {
            // 2.1. 获取 request 中的参数
            Map<String, String[]> parameterMap = request.getParameterMap();
            String method = request.getMethod();
            // 2.2. 对不同请求方式进行参数过滤
            if (CollectionUtils.isEmpty(parameterMap)
                    && (HttpMethod.PUT.name().equals(method)
                    || HttpMethod.POST.name().equals(method))
            ) {
                // 2.1.1 排除 joinPoint.getArgs() 含有的敏感字段
                String params = excludeParam(joinPoint.getArgs(), controllerLog.excludeParamNames());
                sysOperateLog.setOperatorParam(substring(params, 0, 2000));
            } else {
                // 2.1.2 排除 其他请求 含有的敏感字段
                HashMap<String, String[]> params = new HashMap<>(parameterMap);
                for (String excludeParam : controllerLog.excludeParamNames()) {
                    params.remove(excludeParam);
                }
                sysOperateLog.setOperatorParam(substring(JSONUtil.toJsonStr(params), 0, 2000));
            }
        }
        // 3. 是否保存响应参数
        if (controllerLog.isSaveResponseData()) {
            // 3.1 响应参数设置（0 , 2000 ，防止超出数据库最大限制）
            sysOperateLog.setJsonResult(substring(JSONUtil.toJsonStr(jsonResult), 0, 2000));
        }
    }

    /**
     * 过滤敏感字段
     *
     * @param args              字段信息
     * @param excludeParamNames 需要排除的参数名
     */
    private String excludeParam(Object[] args, String[] excludeParamNames) {
        // 1. 对象为空直接返回
        if (ObjectUtils.isEmpty(args)) return "";
        // 2. 遍历对象排除对应属性
        for (Object arg : args) {
            if (isFilterObject(arg)) {
                continue;
            }
            // 2.1 解析对象字段
            Class<?> aClass = arg.getClass();
            Field[] declaredFields = aClass.getDeclaredFields();
            // 2.2 记录每个对象的排除数量
            int count = excludeParamNames.length;
            for (Field declaredField : declaredFields) {
                // 2.3 判断对象字段名是否被排除   ArrayUtils.contains也可以
                if (ArrayUtil.contains(excludeParamNames, declaredField.getName())) {
                    --count;
                    declaredField.setAccessible(true);
                    try {
                        declaredField.set(arg, null);
                    } catch (IllegalAccessException e) {
                        log1.error("排除字段发生错误 {}", declaredField.getName());
                    }
                }
                // 2.4 排除完字段终止本次循环
                if (count == 0) break;
            }
        }
        // 3. 返回 json 字符串
        return JSONUtil.toJsonStr(args);
    }


    /**
     * 异步存储日志信息
     *
     * @param sysOperateLog 日志信息
     * @return 返回一个 Runnable 对象
     */
    private Runnable saveLogTask(SysOperateLog sysOperateLog) {
        return () -> {
            // 1. 获取 ip 真实地址
            sysOperateLog.setOperatorLocation(AddressUtil.getRealAddressByIP(sysOperateLog.getOperatorIp()));
            // 2. 保存日志信息到数据库
            sysOperateLogService.save(sysOperateLog);
        };
    }


    /**
     * 截取字符串
     *
     * @param str   字符串
     * @param start 开始
     * @param end   结束
     * @return 结果
     */
    private String substring(final String str, int start, int end) {
        if (str == null) {
            return "";
        }
        if (end < 0) {
            end = str.length() + end;
        }
        if (start < 0) {
            start = str.length() + start;
        }
        if (end > str.length()) {
            end = str.length();
        }
        if (start > end) {
            return "";
        }
        if (start < 0) {
            start = 0;
        }
        if (end < 0) {
            end = 0;
        }
        return str.substring(start, end);
    }


    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @SuppressWarnings("rawtypes")
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Object value : collection) {
                return value instanceof MultipartFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Object value : map.entrySet()) {
                Map.Entry entry = (Map.Entry) value;
                return entry.getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
                || o instanceof BindingResult;
    }

}
